﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using RaytracerLib;
using RaytracerLib.Materials;

namespace Raytracer.PropertyGridDecorators
{
    public class MaterialConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext a_context,
            Type a_source_type)
        {
            if (a_source_type == typeof(string))
                return true;

            return base.CanConvertFrom(a_context, a_source_type);
        }

        public override bool CanConvertTo(ITypeDescriptorContext a_context,
            Type a_destination_type)
        {
            if (a_destination_type == typeof(Material))
                return true;

            return base.CanConvertTo(a_context, a_destination_type);
        }

        public override object ConvertTo(ITypeDescriptorContext a_context,
            CultureInfo a_culture, object a_value, Type a_destination_type)
        {
            if (a_destination_type == typeof(string))
                return (a_value as Material).Name;

            return base.ConvertTo(a_context, a_culture, a_value, a_destination_type);
        }

        public override object ConvertFrom(ITypeDescriptorContext a_context,
            CultureInfo a_culture, object a_value)
        {
            if (a_value is String)
            {
                var material = (a_context.Instance as RenderableObjectProperties).Material;
                return material.Materials[a_value as String];
            }

            return base.ConvertFrom(a_context, a_culture, a_value);
        }

        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override StandardValuesCollection GetStandardValues(
            ITypeDescriptorContext a_context)
        {
            var material = (a_context.Instance as RenderableObjectProperties).Material;
            return new StandardValuesCollection(material.Materials.ToList());
        }
    }
}